import 'package:flutter/material.dart';
import 'package:schedule_self_client/api/schedule_self_server/task.dart';
import 'package:schedule_self_client/api/schedule_self_server/task_api.dart';
import 'package:schedule_self_client/api/schedule_self_server/task_list_resp.dart';

@Deprecated(
    'refer to microsoft todo app, this class no longer recommended, Use `TaskListPageV2`')
class TaskListPage extends StatefulWidget {
  const TaskListPage({super.key});

  @override
  State<TaskListPage> createState() => _TaskListPageState();
}

class _TaskListPageState extends State<TaskListPage> {
  final List<Task> _tasks = [];
  bool _isLoading = false;
  int _currentPage = 1;
  final _scrollController = ScrollController();
  String _loadingMsg = '查询中...';

  @override
  void initState() {
    _loadTaskList();
    super.initState();
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('待办事项'),
      ),
      body: NotificationListener<ScrollNotification>(
        onNotification: (notification) {
          if (notification is ScrollEndNotification &&
              notification.metrics.extentAfter < 20) {
            _loadTaskList();
          }
          return true;
        },
        child: ListView.builder(
          physics: const AlwaysScrollableScrollPhysics(),
          itemCount: _tasks.length + (_isLoading ? 1 : 0),
          itemBuilder: (BuildContext context, int index) {
            if (index == _tasks.length) {
              return Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  const SizedBox(
                      width: 20,
                      height: 20,
                      child: CircularProgressIndicator(
                        strokeWidth: 2,
                      )),
                  const SizedBox(width: 10),
                  Text(_loadingMsg)
                ],
              );
            }
            return _buildTaskCard(_tasks[index], index);
            // return SizedBox(height: 100, child: Text(_tasks[index].name));
          },
          controller: _scrollController,
        ),
      ),
    );
  }

  _loadTaskList() async {
    if (_isLoading) {
      return;
    }
    setState(() {
      _isLoading = true;
    });
    TaskListResp taskListResp = await TaskApi.getTasks(_currentPage, 10);
    setState(() {
      if (_tasks.length == taskListResp.totalCount) {
        _loadingMsg = '没有更多了';
      } else {
        _tasks.addAll(taskListResp.data);
        _currentPage++;
      }
      _isLoading = false;
    });
  }

  Widget _buildTaskCard(Task task, int index) {
    return Card(
      child: Column(
        children: [
          CheckboxListTile(
            selectedTileColor: Colors.red,
            title: Text(task.name),
            subtitle: Text(task.description),
            value: task.isComplete(),
            onChanged: (value) {
              setState(() {
                if (value != null) {
                  Task newTask =
                      task.rebuild((it) => it.completeFlag = value ? 1 : 0);
                  _tasks.replaceRange(index, index + 1, [newTask]);
                }
              });
            },
          )
        ],
      ),
    );
  }
}
